<?php
namespace api\common\helpers;

/**
 * author:holis
 * des:公共工具方法
 * datetime:2020 2020-02-19 14:49
 */
class Tools{

    /**
     * author:holis
     * des:post请求
     * datetime:2020 2020-02-19 14:50
     */
    public function curlpost($url,$post_data,$timeout=5,$httpHeader = array()){
        $urlArr = explode(':',$url);
        $protocol = !empty($urlArr[0])?$urlArr[0]:'http';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
        if($protocol=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        if($httpHeader){
            //如果$post_data是json，需要加请求头array('Content-Type: application/json')
            curl_setopt($ch, CURLOPT_HTTPHEADER,$httpHeader);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        //打印获得的数据
        return $output;
    }


    /**
     * author:holis
     * des:导出csv
     * datetime:2020 2020-02-19 23:09
     */
    function exportCsv($filename, $head, $dataArray)
    {
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
        header('Cache-Control: max-age=0');

        // 从数据库中获取数据，为了节省内存，不要把数据一次性读到内存，从句柄中一行一行读即可
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');
        // 输出Excel列名信息
        foreach ($head as $i => $v) {
            // CSV用Excel打开时，不支持UTF-8编码，而支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }
        // 将数据通过fputcsv写到文件句柄
        fputcsv($fp, $head);
        // 计数器
        $cnt = 0;
        // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;

        // 逐行取出数据，不浪费内存
        foreach ($dataArray as $item) {
            $cnt++;
            if ($limit == $cnt) {
                //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $cnt = 0;
            }
            foreach ($item as $i => $v) {
                $item[$i] = iconv('utf-8', 'gbk', $v);
            }
            fputcsv($fp, $item);
        }
    }


    /**
     * author:holis
     * des:导出excel
     * datetime:2020 2020-02-19 23:09
     */
    public function exportExcel($filename,array $titles, array $dataArray, $bigTitle='')
    {
        // 后缀
        $suffix = substr($filename, strrpos($filename, '.'));
        empty($titles) && die('标题数组不能为空！');
        //empty($dataArray) && die('数据数组不能为空！');
        !in_array($suffix, ['.xls', '.xlsx']) && die('文件名格式错误！');

        $oExcel = new \PHPExcel();
        $oExcel->setActiveSheetIndex(0);
        $sheet = $oExcel->getActiveSheet();

        // 行索引
        $rowIndex = $bigTitle!=''? 2:1;

        // 设置大标题
        if ($bigTitle != '') {
            $sheet->mergeCells('A1:'. chr(64+count($titles)) .'1');
            $sheet->getStyle('A1')->applyFromArray([
                'font' => ['bold'=>true],
                'alignment' => ['horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER]
            ]);
            $sheet->setCellValue('A1', $bigTitle);
        }

        // 设置标题 A1 B1 C1 ....
        $colIndex = 0;
        $fieldsMap = [];
        foreach ($titles as $key => $title) {
            $fieldsMap[] = $key;
            $sheet->setCellValue(chr(65+$colIndex) . $rowIndex, $title);
            $colIndex++;
        }
        // 设置内容 A1 B1 C1 ....   A2 B2 C2 ....
        $rowIndex++;
        foreach ($dataArray as $key => $value)
        {
            foreach ($fieldsMap as $colIndex => $field) {
                $sheet->setCellValue(chr(65+$colIndex).$rowIndex, $value[$field]);
            }
            $rowIndex++;
        }

        if ($suffix == '.xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } else {
            header('Content-Type: application/vnd.ms-excel');
        }
        header('Content-Disposition: attachment;filename="'. $filename .'"');
        $oWriter = \PHPExcel_IOFactory::createWriter($oExcel, 'Excel2007');
        $oWriter->save('php://output');
        $oExcel->disconnectWorksheets();
        exit;
    }

}